<?php

namespace app\admin\controller\express;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 物流包裹管理
 *
 * @icon fa fa-circle-o
 */
class Package extends Backend
{

    /**
     * Package模型对象
     * @var \app\admin\model\express\Package
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Package;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);
        $batch_id = $this->request->param('ids', '');
        if (false === $this->request->isAjax()) {
            $this->assignconfig('batch_id', $batch_id);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $batch_id = $this->request->param('batch_id', '');
        $w = [];
        if ($batch_id) {
            $w['batch_id'] = $batch_id;
        }
        $list = $this->model->with(['user', 'track', 'batch'])
            ->where($where)->where($w)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    public function batch($ids = null)
    {

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $packageList = $this->model->field(['id', 'status', 'batch_id'])->whereIn('id', $ids)->where(['status' =>2])->select();
            if(empty($packageList)){
                throw new Exception("订单不存在或状态不对");
            }
            $ids = array_column($packageList, 'id');
            $batchId = intval($params['batch_id']);
            $type = trim($params['type']);
            $batch = new \app\admin\model\express\Batch();
            $track = new \app\admin\model\express\Track();
            $trackInfo = $track->order("weigh desc")->find();
            $trackId = $trackInfo->id;
            $trackId = 0;
            if ($type == 'new') {
                $batch_no = $batch->getBatchNo();
                $batch->save([
                    'batch_no' => $batch_no,
                    'number' => count($ids),
                    'state' => $trackId,
                ]);
                $batchId = $batch->id;
            } else if ($type == "old") {
                $batch_check = $batch->where(['id' => $batchId])->find();
                if ($batch_check == null) {
                    $this->error("该批次不存在");
                }
                $trackId = $batch_check->state;
            }

            $this->model->where('id', 'in', $ids)->update(['status' =>3, 'track_id' => $trackId, 'batch_id' => $batchId, 'outtime' => time()]);
            $number = $this->model->where('batch_id', $batchId)->count();
            (new \app\admin\model\express\Batch())->where('id', $batchId)->setField('number', $number);

            $packageTrackData = [];
            foreach ($ids as $package) {
                array_push($packageTrackData, [
                    'package_id' => $package,
                    'track_id' => $trackId,
                    'admin_id' => $this->auth->id,
                ]);
            }

            $packageTrack = new \app\admin\model\express\Packagetrack();
           // $packageTrack->saveAll($packageTrackData);

            Db::commit();
            $result = true;
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function delbatch(){
        $id = (int)$this->request->param('id');
        if($id<1){
            $this->error("缺少参数");
        }
        $package = Db::name("express_package")->where(['id'=>$id])->field(['id','batch_id'])->find();
        if(empty($package)){
            $this->error("数据不存在");
        }
        Db::startTrans();
        try{
            Db::name("express_package")->where(['id'=>$id])->update(['batch_id'=>0,'status'=>2,'track_id'=>0]);
            Db::name("express_packagetrack")->where(['package_id'=>$id])->delete();
            $num = Db::name("express_package")->where(['batch_id'=>$package['batch_id']])->count();
            Db::name("express_batch")->where(['id'=>$package['batch_id']])->setField('number',$num);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success("ok");
    }

}
